# 封装requests请求,记录日志
import requests
import urllib3

from common import logger


class Requestutil:
    # 使用session，可以保存cookie信息
    session = requests.session()

    # 封装统一请求
    @classmethod
    def send_all_request(cls, **kwargs):
        # 忽略https的请求协议提醒
        urllib3.disable_warnings()
        res = Requestutil.session.request(**kwargs)
        # 通过get方式，如果参数不存在不会报错（KeyError），返回默认值
        method_ = kwargs.get('method', None)
        url_ = kwargs.get('url', None)
        params_ = kwargs.get('params', None)
        data_ = kwargs.get('data', None)
        json_ = kwargs.get('json', None)
        headers_ = kwargs.get('headers', None)
        # 请求方式转为大写
        method__upper = method_.upper()
        if method__upper == 'GET':
            logger.info(f'请求路径：{url_}')
            logger.info(f'请求方式：{method__upper}')
            if params_ is not None:
                logger.info(f'请求参数：{params_}')
            if headers_ is not None:
                logger.info(f'请求headers参数：{headers_}')
            logger.info(f'响应数据：{res.text}')
        elif method__upper == 'POST':
            logger.info(f'请求路径：{url_}')
            logger.info(f'请求方式：{method__upper}')
            if params_ is not None:
                logger.info(f'请求params_参数：{params_}')
            if data_ is not None:
                logger.info(f'请求data_参数：{data_}')
            if json_ is not None:
                logger.info(f'请求json_参数：{json_}')
            if headers_ is not None:
                logger.info(f'请求headers参数：{headers_}')
            logger.info(f'响应数据：{res.text}')
        else:
            logger.info(f'请求路径：{url_}')
            logger.info(f'请求方式：{method__upper}')
            logger.info(f'请求参数：{kwargs}')
            logger.info(f'响应数据：{res.text}')
        logger.info('===================此测试案例结束=====================')
        return res


if __name__ == '__main__':
    url = 'https://www.wanandroid.com/article/list/0/json'
    Requestutil.send_all_request(method='get', url=url)
